// import router from "@/router/router";
import axios from 'axios'
import Cookies from 'js-cookie'
import { message } from 'antd'
import { baseURL} from '../baseURL'

// 请求拦截器
axios.interceptors.request.use(function (config) { // 让每个请求携带token
    let cookiesTemp = Cookies.get('token');
    if (cookiesTemp)  config.headers['token'] = cookiesTemp
    return config;
}, function (error) {
    return Promise.reject(error);
})
// 响应拦截器
axios.interceptors.response.use((response) => {
    // 判断响应结果
    let res = response.data;
    if (+res.code == 444) {
        Cookies.remove('token')
        // router.replace('/login?status=1')
    } else if (+res.code == 307) {
        // router.replace('/updataing');
        return response;
    } else if(+res.code === 200) {
        if (response.config.config && response.config.config.showTips) {
            message.success(res.msg || "操作成功!")
        }
        return response;
    } else if([400, 402, 500, 404].includes(+res.code)) {
        if (response.config.config && response.config.config.showTips) {
            message.error(res.msg)
        }
        return response;
    } else {
        return response;
    }
}, (error) => {
    message.error(error)
    return Promise.reject(error);
});

axios.defaults.baseURL = baseURL;

// 二次封装HTTP REQUEST METHODS
/**
 * GET
 * @param {*} url 
 * @param {*} params 
 * @param {object} options 非必须
 * @returns 
 */
export const GET = (url, params, options) => {
    // 合并配置项
    let config = options;
    if (typeof options === 'object' && !Array.isArray(options)) {
        Object.assign(config, options);
    }
    return new Promise((resolve, reject) => {
        axios({
            method: 'get',
            url,
            params,
            config,
        }).then(res => {
            resolve(res);
        })
    });
}

/**
 * POST
 * @param {*} url 
 * @param {*} params 
 * @param {object} options 
 * @returns 
 */
export const POST = (url, data, options) => {
    // 合并配置项
    let config = options;
    return new Promise((resolve, reject) => {
        axios({
            method: 'post',
            url,
            data,
            config,
        }).then(res => {
            resolve(res);
        })
    });
}

export default axios
